package com.maas.util.mybatis.jpa.littlenb.conditions.plus.core.toolkit.util;

import com.littlenb.mybatisjpa.util.PersistentUtil;
import org.apache.commons.lang3.StringUtils;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * <p>
 * PlusPersistentUtil
 * </p>
 *
 * @author zxm
 * @date 2021/07/09 13:53
 * @since 2021/07/09 13:53
 */
public class MyBatisPlusPersistentUtil extends PersistentUtil {
    /**
     *
     *利用java8 中 lambda 方法引用获取字段属性
     * getFieldName(Person::getName)
     * @param func
     * @param <T>
     * @return
     */
    public static <T> String getColumnName(PropertyFunc<T, ?> func,Class oneClass) {
        try {
            // 通过获取对象方法，判断是否存在该方法
            Method method = func.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(Boolean.TRUE);
            // 利用jdk的SerializedLambda 解析方法引用
            SerializedLambda serializedLambda = (SerializedLambda) method.invoke(func);
            String getter = serializedLambda.getImplMethodName();


            String fieleName = resolveFieldName(getter);

            Field field = FieldUtil.getField(oneClass,fieleName);
            if(field!=null){
                return getColumnName(field);
            }else{
                return "";
            }


        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    private static String resolveFieldName(String getMethodName) {
        if (getMethodName.startsWith("get")) {
            getMethodName = getMethodName.substring(3);
        } else if (getMethodName.startsWith("is")) {
            getMethodName = getMethodName.substring(2);
        }
        // 小写第一个字母
        return firstToLowerCase(getMethodName);
    }

    private static String firstToLowerCase(String param) {
        if (StringUtils.isBlank(param)) {
            return "";
        }
        return param.substring(0, 1).toLowerCase() + param.substring(1);
    }
}
